<?php

require_once "pear/XML/Unserializer.php";
require_once "pear/XML/Serializer.php";

class FileXML{
	
	var $configfile = "./user/files.xml";
	
	function _readFileList(){
		$unserializer_options = array('forceEnum' => array('f'), 'parseAttributes'=>true );
		$unserializer = &new XML_Unserializer($unserializer_options);
		$result = $unserializer->unserialize( dirname(__FILE__) ."/" . $this->configfile, true);
		$files = $unserializer->getUnserializedData();
		return $files;		
	}
	
	function _writeFileList($wFiles){
		$serializer_options = array (
		   'addDecl' => TRUE,
		   'encoding' => 'utf-8',
		   'indent' => '  ',
		   'rootName' => 'files',
		   'mode' => 'simplexml',
		  'defaultTagName' => 'file',
		  'scalarAsAttributes'=> array('file'=>true)
		);
		$Serializer = &new XML_Serializer($serializer_options);
		$status = $Serializer->serialize($wFiles);
		$data = $Serializer->getSerializedData();
		$handle = fopen( dirname(__FILE__)."/" . $this->configfile, 'w');
		fwrite($handle, $data); 
		fclose($handle);		
		
	}
	
	////////////////////////////////////////////////////Public Methods
		
	function push_new_file($folder, $fileName, $user){
		$files = $this->_readFileList();
		foreach($files['file'] as $f){
			if($fileName == $f['name'])
				if($folder == $f['folder'])
					return array('valid'=>0, 'error'=>"This file already exsits in this folder");
		}
		
		$fileObj['name'] = $fileName;
		$fileObj['folder'] = $folder;
		$fileObj['checkedIn'] = 1;
		$fileObj['checkedInOutBy'] = $user;
		
		array_push($files['file'], $fileObj);
		$this->_writeFileList($files);
		
		return array('valid'=>1, 'fileName'=>$fileName);
	}
	
	function getCheckedInValue($folderName, $fileName){
		$files = $this->_readFileList();
		foreach($files['file'] as $f){
			if($f['name'] == $fileName && $f['folder'] == $folderName){
				return array('valid'=>1, 'checkedInValue'=>$f['checkedIn'], 'user'=>$f['checkedInOutBy']);
			}
		}
		return array('valid'=>0, 'error'=>'File does not exsist in folder');
	}
	
	function updateCheckOut($folderName, $fileName, $value, $name){
		$files = $this->_readFileList();
		for($i = 0; $i < count($files['file']); $i++){
			if($files['file'][$i]['name'] == $fileName && $files['file'][$i]['folder'] == $folderName){
				$files['file'][$i]['checkedIn'] = $value;
				$files['file'][$i]['checkedInOutBy'] = $name;
				$this->_writeFileList($files);
				return array('valid'=>1, 'file'=>$fileName);
			}
				
		}
		return array('valid'=>0, 'error'=>'File or folder does not exsist.');
	}
}
?>
